package inits

import (
	"fmt"
	"github.com/spf13/viper"
	"log"
	"zg4/zk1/server/global"
)
import "github.com/go-redis/redis/v8"
import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func Inits() {
	InitConfig()
	InitMysql()
	InitRedis()
}

func InitMysql() {
	var config = global.Config.Mysql
	var err error
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.User, config.Password, config.Host, config.Port, config.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	log.Println("mysql init success")
}

func InitRedis() {
	var config = global.Config.Redis
	global.RDB = redis.NewClient(&redis.Options{
		Addr:     config.Addr,
		Password: config.Password, // no password set
		DB:       config.DB,       // use default DB
	})
	log.Println("redis init success")
}

func InitConfig() {

	v := viper.New()
	v.SetConfigFile("./dev.yaml")
	err := v.ReadInConfig()
	if err != nil {
		return
	}
	err = v.Unmarshal(&global.Config)
	if err != nil {
		return
	}
	log.Println("config init success")
}
